import pandas as pd
from function.merger import rri_deal

# 读取数据
rricsv = rri_deal('1007rri.txt')

# 转换 timestamp 列为 datetime 格式
rricsv['time'] = pd.to_datetime(rricsv['timestamp'], unit='ms')

# 先本地化为 UTC，再转换为上海时间
rricsv['time'] = rricsv['time'].dt.tz_localize('UTC').dt.tz_convert('Asia/Shanghai')

# 使用 dt.strftime 来格式化时间
rricsv['formatted_time'] = rricsv['time'].dt.strftime("%Y-%m-%d %H:%M:%S")

# 过滤出 sqi 为 100 的数据
need_rricsv = rricsv[rricsv['sqi'] == 100]

# 将 formatted_time 列转换为 datetime 类型
need_rricsv['formatted_time'] = pd.to_datetime(need_rricsv['formatted_time'])

# 检查连续性
need_rricsv = need_rricsv.sort_values(by='formatted_time')  # 确保按时间排序
need_rricsv['time_diff'] = need_rricsv['formatted_time'].diff().dt.total_seconds()

# 设定一个时间间隔阈值（例如：60秒）
threshold = 60  # 这里以秒为单位，如果你的数据时间间隔更小，可以调整这个值

# 找到不缺失的连续段
continuous_segments = []
start_time = None

for i in range(len(need_rricsv)):
    if i == 0:  # 第一个元素
        start_time = need_rricsv['formatted_time'].iloc[i]
    elif need_rricsv['time_diff'].iloc[i] <= threshold:  # 如果没有缺失
        if i == len(need_rricsv) - 1:  # 如果是最后一个元素
            continuous_segments.append((start_time, need_rricsv['formatted_time'].iloc[i]))
    else:  # 如果存在缺失
        continuous_segments.append((start_time, need_rricsv['formatted_time'].iloc[i - 1]))
        start_time = need_rricsv['formatted_time'].iloc[i]  # 更新起始时间

# 输出不缺失的连续段
for start, end in continuous_segments:
    print(f"Continuous segment from {start} to {end}")


